<template>
  <div class="bg-shell">
    <video
      v-if="videoUrl"
      :src="videoUrl"
      class="bg-media"
      autoplay
      muted
      loop
      playsinline
    />
    <div
      v-else-if="imageUrl"
      class="bg-media"
      :style="{ backgroundImage: `url(${imageUrl})` }"
    />

    <div class="bg-mask" :style="cssVars" />

    <div class="content">
      <slot />
    </div>
  </div>
</template>

<script setup>
import { shallowRef, computed, watchEffect } from "vue";
import { useStore } from "vuex";
import { openDB, getDataByKey } from "@/util/image";
import videoStorage from "@/util/vide";

const store = useStore();
const imageUrl = shallowRef("");
const videoUrl = shallowRef("");

const blur = computed(() => store.getters["getamount"]);
const alpha = computed(() => store.getters["getopacity"]);

const cssVars = computed(() => ({
  "--blur": blur.value + "px",
  "--alpha": alpha.value / 100,
}));

const preloadImage = (src) =>
  new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = () => resolve(src);
    img.onerror = reject;
    img.src = src;
  });

watchEffect(async () => {
  const useVideo = store.getters["getvide"];
  if (useVideo) {
    imageUrl.value = "";
    videoUrl.value = await videoStorage.getVideoUrl();
  } else {
    videoUrl.value = "";
    const key = store.getters["getimgUrl"];
    if (!key) return;
    try {
      const db = await openDB("web", 1);
      const blob = (await getDataByKey(db, "imglist", key))?.url;
      if (blob) imageUrl.value = await preloadImage(blob);
    } catch (e) {
      console.error("BgShell load image error:", e);
    }
  }
});
</script>

<style scoped>
.bg-shell {
  position: relative;
  width: 100%;
  min-height: 100vh;
  overflow: hidden;
}

.bg-media {
  position: fixed;
  inset: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  background-size: cover;
  background-position: center;
  z-index: -3;
}

.bg-mask {
  position: fixed;
  inset: 0;
  z-index: -2;
  -webkit-backdrop-filter: blur(var(--blur));
  backdrop-filter: blur(var(--blur));
  background: rgba(0, 0, 0, var(--alpha));
}

.content {
  position: relative;
  z-index: 1;
}
</style>
